package com.mars.basic.controller.file;


import com.mars.basic.allmain.po.Picture;
import com.mars.basic.service.PictureService;
import com.mars.common.annotation.MultiRequestBody;
import com.mars.common.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Date;
import java.util.UUID;


@RestController
@RequestMapping("/file")
public class FileController {

    @Autowired
    private PictureService pictureService;

    /**
     * 临时图片上传
     *
     * @return
     */
    @RequestMapping("/upload")
    public R upload(@RequestParam("file") MultipartFile file) {
        File localFile = TenXCOS.toFile(file);
        String url = TenXCOS.upload(localFile, "picture/", "mars-1306600834");
        Picture picture = new Picture();
        picture.setTBucketNam("mars-1306600834");
        picture.setTKey("picture/" + localFile.getName());
        picture.setStatus(MarsConstant.StatusEnum.ENABLE.value());
        picture.setType(MarsConstant.pictureType.MD.type());
        picture.setUrl(url);
        picture.setCreateTime(new Date());
        picture.setName(localFile.getName());
        Picture save = pictureService.getRepo().saveAndFlush(picture);
        if (localFile.delete()) {
            System.out.println("删除成功");
        }
        return R.data(save);
    }

    /**
     * md文件上传
     *
     * @param param
     * @return
     */
    @RequestMapping("/md")
    public R mdUpload(@MultiRequestBody("param") String param) {
        //取出java中对应参数的值
        String filepath = Constants.TX_FILE_PATH;
        String fileName = UUID.randomUUID().toString() + ".md";
        FileUtils.string2File(param, fileName);
        File file = new File(fileName);
        String url = TenXCOS.upload(file, filepath, "mars-1306600834");
        if (file.delete()) {
            System.out.println("删除成功");
        }
        return R.data(url);
    }

}
